745C - Hongcow Builds A Nation - CodeForces Solution


constructive algorithms dfs and similar graphs *1500

Please click on ads to support us..

C++ Code:

#include<bits/stdc++.h>
using namespace std;
#define ll long long
vector<int>adj[1005];
bool vis[1005];
int nodes=1, edges=0;
void dfs(int n) {
    vis[n]=1;
    for(auto it:adj[n])
        if(!vis[it]) {
            nodes++;
            edges+=adj[it].size();
            dfs(it);
        }
}
int main() {
    std::ios_base::sync_with_stdio(0),cin.tie(0),cout.tie(0);
    int n, m, k, u, v;
    cin>>n>>m>>k;
    int a[k];
    for(int i=0; i<k; i++)
        cin>>a[i];
    for(int i=0; i<m; i++) {
        cin>>u>>v;
        adj[u].push_back(v);
        adj[v].push_back(u);
    }
    priority_queue<int>pq;
    ll ans=0;
    for(int i=0; i<k; i++) {
        nodes=1, edges=adj[a[i]].size();
        dfs(a[i]);
        edges/=2;
        ans+=((nodes*(nodes-1)/2)-edges);
        pq.push(nodes);
    }
    ll mx=pq.top();
    for(int i=1; i<=n; i++)
        if(!vis[i]) {
            nodes=1, edges=adj[i].size();
            dfs(i);
            edges/=2;
            ans+=((nodes*(nodes-1)/2)-edges);
            ans+=mx*nodes;
            mx+=nodes;
        }
    cout<<ans;
    return 0;
}


Comments

Submit
0 Comments
More Questions

754B - Ilya and tic-tac-toe game
760A - Petr and a calendar
1573A - Countdown
166A - Rank List
1631B - Fun with Even Subarrays
727A - Transformation from A to B
822B - Crossword solving
1623A - Robot Cleaner
884B - Japanese Crosswords Strike Back
862B - Mahmoud and Ehab and the bipartiteness
429A - Xor-tree
1675C - Detective Task
950A - Left-handers Right-handers and Ambidexters
672B - Different is Good
1C - Ancient Berland Circus
721A - One-dimensional Japanese Crossword
1715B - Beautiful Array
60B - Serial Time
453A - Little Pony and Expected Maximum
1715A - Crossmarket
1715C - Monoblock
1512C - A-B Palindrome
1679B - Stone Age Problem
402A - Nuts
792A - New Bus Route
221A - Little Elephant and Function
492C - Vanya and Exams
1369B - AccurateLee
892B - Wrath
999A - Mishka and Contest